// pages/square/my.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "我的广场", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    listType: 0,
    classArr: [{
      id: 0,
      name: '最新'
    }, {
      id: 1,
      name: '最多赞'
    }],
    classId: 0,
    forumList: [],
    forumListGl: [],//攻略列表
    isHeightMode: false,
    showDelDom: false,

    authData: {
      authType: '0', //0表示使用登录弹窗  1表示使用完善昵称头像弹窗 2表示直接弹出头像昵称选择框
      authUsername: "false", //是否已经授权头像昵称
    },
    showLogin: false, //是否显示授权弹窗
    showWsInfoDom: false, //直接显示头像昵称弹窗
    showPrivacyFlag: app.globalData.showPrivacyFlag,

    openid: '',
    is_nickAndHead: 0,
    shareTitle: '',
    shareImg: '',

    sort: 1, //1:最新 2：最热
    page: 1, //当前页数
    pageGl:1,
    isLoadingEnd: 0, //0:数据未加载完 1:数据已加载完
    isLoadingEndGl: 0, //0:数据未加载完 1:数据已加载完
    isloading: false,

    userInfo: [],
    bgzTotal: 0,
    gzTotal: 0,
    likeTotal: 0,
    scTotal: 0,
    zanTotal: 0,
    isOne: 1,
    is_one_gl:1,//是否是第一次加载攻略 1：是 2：不是
    delId: 0,
    delRow: 0,
    showCircle: true,
    headerUrl: '',
    gameList: [],

    isHaveMore:true, 
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  chooseClass(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    this.setData({
      classId: id
    });

    //判断是切换的圈子还是攻略
    if(that.data.listType==0){
      //圈子
      if (id == 0) {
        //最新
        that.setData({
          sort: 0,
          page: 1,
          forumList: []
        });

        //缓存圈子是最新还是最多赞
        wx.setStorageSync('myQzSort', 0);
        //调用加载
        that.getList(1, 0, 0);
      } else {
        //推荐
        that.setData({
          sort:1,
          page: 1,
          forumList: []
        });
        //缓存圈子是最新还是最多赞
        wx.setStorageSync('myQzSort', 1);
        //调用加载
        that.getList(1, 1, 0);
      }
    }else if(that.data.listType==2){
      //攻略
        if (id == 0) {
        //最新
        that.setData({
          sort: 0,
          pageGl: 1,
          forumListGl: []
        });

        //缓存攻略是最新还是最多赞
        wx.setStorageSync('myGlSort', 0);
        //调用加载
        that.getListGl(1, 0, 0);
      } else {
        //推荐
        that.setData({
          sort: 1,
          pageGl: 1,
          forumListGl: []
        });
        //缓存攻略是最新还是最多赞
        wx.setStorageSync('myGlSort', 1);
        //调用加载
        that.getListGl(1, 1, 0);
      }
    }
  },
  //发布
  public(){
    var that = this;
    var listType = that.data.listType;
    //发布圈子
    if(listType=="0"){
      wx.navigateTo({
        url: '/pages/square/public1',
      })//发布悦攻略
    }else if(listType=="2"){
      wx.navigateTo({
        url: '/pages/square/public3',
      })
    }else{
      //发布麓客局
      wx.navigateTo({
        url: '/pages/square/public2',
      })
    }
  },
  //跳转至麓客局详情页
  goGameDetail(e) {
    var that = this;
    var row = e.currentTarget.dataset.index;
    var id = that.data.gameList[row].id;
    var gameOpenid = that.data.gameList[row].openid;
    that.addHeaderUrl();
    //跳转自己的组局详情
    wx.redirectTo({
      url: '/pages/square/myPart?id=' + id
    });
  },

  //热门话题跳转至话题详情
  goDetail(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    if (id == that.data.tid) {
      return;
    }
    that.addHeaderUrl();
    wx.redirectTo({
      url: '/pages/square/talk?tid=' + id
    });
  },

  //跳转至帖子详情
  goPostDetail(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;

    that.addHeaderUrl();
    wx.redirectTo({
      url: '/pages/square/commentDetail?id=' + id
    });
  },


  //跳转到列表页
  toList(e) {
    var that = this;
    var menuIndex = e.currentTarget.dataset.flag;
    that.addHeaderUrl();
    wx.navigateTo({
      url: '/pages/square/list?menuIndex=' + menuIndex
    });
  },

  //将回跳url写入缓存
  addHeaderUrl() {
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array) {
      if (this.data.headerUrl == headerUrlList[headerUrlList.length - 1]) {
        //与上一个回跳链接相同则不添加
        return;
      }
      headerUrlList.push(this.data.headerUrl);
      wx.setStorageSync('headerUrlList', headerUrlList);
    } else {
      headerUrlList = [];
      headerUrlList.push(this.data.headerUrl)
      wx.setStorageSync('headerUrlList', headerUrlList);
    }
  },

  //点击圈子
  qz() {
    let that = this;
    that.setData({
      listType: 0,
      classId:wx.getStorageSync('myQzSort')
    })

  },
  ygl(){
    let that = this;
    that.setData({
      listType: 2,
      classId:wx.getStorageSync('myGlSort')
    });

    //判断是否是第一次调用
    if(that.data.is_one_gl==1){
      that.setData({
        is_one_gl:0,
      });
      that.getListGl(1, 0, 0);
    }

  },
  //点击麓客局
  lkj() {
    let that = this;
    that.setData({
      listType: 1
    })
  },
  //删除某个帖子
  delPost(e) {
    var index = e.currentTarget.dataset.id;
    var delId = this.data.forumList[index].id;
    this.setData({
      showDelDom: true,
      delId: delId,
      delRow: index
    })
  },
  //确认删除
  sureDel() {
    var that = this;
    this.setData({
      showDelDom: false
    });

    wx.showLoading({
      title: '数据处理中...'
    });

    wx.request({
      url: that.data.baseUrl + 'delForum.php',
      method: 'POST',
      data: {
        openid: that.data.openid,
        id: that.data.delId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        app.showTip(res.data.msg);
        if (res.data.status == 1) {
          //后台请求成功
          var forumList = that.data.forumList;
          forumList.splice(that.data.delRow, 1);
          that.setData({
            forumList: forumList
          });
        } else {
          //后台请求失败
          //app.showTip(res.data.msg);
          return;
        }
      },
      fail: function(res) {
        wx.hideLoading();
      }
    });
  },
  //取消
  cancel() {
    let that = this;
    that.setData({
      showDelDom: false
    })
  },
  // 预览图片
  previewImage(e) {
    let {
      sources,
      index
    } = e.currentTarget.dataset
    sources.filter(i => {
      i.type = i.type == 2 ? 'video' : 'image'
      i.poster = i.imgUrl
    })
    console.log("sources:", sources)
    wx.previewMedia({
      sources,
      current: index
    })
  },

  // 视频加载完成，改变视频的宽高
  videometa(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = res.windowWidth;

        //算出当前宽度下高度的数值
        height = proportion * windowWidth;
        that.setData({
          height,
          width: windowWidth
        });
      }
    })
  },
// 视频加载完成，改变视频的宽高
videometa2(e) {
  var that = this;
  //获取系统信息
  wx.getSystemInfo({
    success(res) {
      //视频的高
      var height = e.detail.height;

      //视频的宽
      var width = e.detail.width;

      //算出视频的比例
      var proportion = height / width;

      //res.windowWidth为手机屏幕的宽。
      var windowWidth = 331;

      //算出当前宽度下高度的数值
      height = proportion * windowWidth;
      that.setData({
        height,
        width: windowWidth
      });
    }
  })
},
  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    wx.getImageInfo({
      src: e.currentTarget.dataset.sources[0],
      success: function(res) {
        console.log(res.width, res.height); // 这里获取的宽高是正确的
        res.height >= res.width && this.setData({
          isHeightMode: true
        })
      },
      fail: function(err) {
        console.log(err);
      }
    });
  },

  //收藏
  collect(e) {
    var that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addSc.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumList[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumList[' + index + '].collect.status']: "1",
              ['forumList[' + index + '].collect.num']: parseInt(that.data.forumList[index].collect.num) + 1,
              scTotal: parseInt(that.data.scTotal) + 1
            })

          } else {
            that.setData({
              ['forumList[' + index + '].collect.status']: "0",
              ['forumList[' + index + '].collect.num']: parseInt(that.data.forumList[index].collect.num) - 1,
              scTotal: parseInt(that.data.scTotal) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function(res) {
        wx.hideLoading();
      }
    });
  },

  //点赞
  help(e) {
    var that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addZan.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumList[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumList[' + index + '].help.status']: "1",
              ['forumList[' + index + '].help.num']: parseInt(that.data.forumList[index].help.num) + 1,
              likeTotal: parseInt(that.data.likeTotal) + 1
            })

          } else {
            that.setData({
              ['forumList[' + index + '].help.status']: "0",
              ['forumList[' + index + '].help.num']: parseInt(that.data.forumList[index].help.num) - 1,
              likeTotal: parseInt(that.data.likeTotal) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function(res) {
        wx.hideLoading();
      }
    });
  },

  //处理完善信息
  addWxInfo() {
    this.setData({
      ['authData.authType']: 1,
      showLogin: true
    });
  },

  //处理完善信息
  addWxInfo2() {
    this.setData({
      showWsInfoDom: true
    });
  },

  //接收子组件电话授权及头像昵称授权后后返回的值
  returnVal(e) {
    //授权完头像昵称
    this.setData({
      is_nickAndHead: e.detail.is_nickAndHead,
      ['userInfo.head']: e.detail.head,
      ['userInfo.nickname']: e.detail.nickname
    });

    app.showTip('个人信息已完善');
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //赋值回跳本页的url
    that.setData({
      headerUrl: '/pages/square/my'
    });
    //判断缓存里是否有值
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array && headerUrlList.length > 0) {
      //返回中有值
      that.setData({
        ['defaultData.goUrl']: headerUrlList[headerUrlList.length - 1]
      });
    }

    //获取发布麓客局标识
    var listType = wx.getStorageSync('listType');
    if (listType == 1 || listType == '1') {
      that.setData({
        listType: 1
      });
      //清空缓存
      wx.setStorageSync('listType', 0);
    }

    //初始化圈子和攻略最新或推荐排序的缓存
    wx.setStorageSync('myQzSort', 0);
    wx.setStorageSync('myGlSort', 0);

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getMyPageInfo(res.data.openid);
              },
              fail: function(res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getMyPageInfo(openid);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getMyPageInfo(openid) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getMyPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        myOpenid: openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            //mySf: res.data.mySf,
            forumList: res.data.forumList,
            is_nickAndHead: res.data.is_nickAndHead,
            isLoadingEnd: res.data.isLoadingEnd,
            userInfo: res.data.userInfo,
            bgzTotal: res.data.bgzTotal,
            gzTotal: res.data.gzTotal,
            likeTotal: res.data.likeTotal,
            scTotal: res.data.scTotal,
            zanTotal: res.data.zanTotal,
            isOne: 0,
            gameList: res.data.gameList
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function(res) {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function(res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    var timeout = setTimeout(function() {
      that.setData({
        showCircle: false
      });
      clearTimeout(timeout)
    }, 100);

    if (that.data.isOne == 0) {
      //刷新数字列表
      wx.request({
        url: that.data.baseUrl + 'fleshForumNum.php',
        method: 'POST',
        data: {
          'openid': that.data.openid
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.status == 1) {
            that.setData({
              bgzTotal: res.data.bgzTotal,
              gzTotal: res.data.gzTotal,
              likeTotal: res.data.likeTotal,
              scTotal: res.data.scTotal,
              zanTotal: res.data.zanTotal
            })
          }
        },
        fail: function(res) {

        }
      });
    }

    //更新showPrivacyFlag
    this.setData({
      showPrivacyFlag: app.globalData.showPrivacyFlag
    });

    //判断是否删除了攻略帖子
    var delId = wx.getStorageSync('delGlId');
    if(delId>0&&delId!=undefined){
      let list = that.data.forumListGl;
      let row=0;
      for(var i=0;i<list.length;i++){
        if(list[i]['id']==delId){
          row=i;
          break;
        }
      }
 
      // 使用splice删除元素
      list.splice(row, 1);

      //重新整理列表数组
      that.setData({
        forumListGl:list
      });
      //清空缓存
      wx.setStorageSync('delGlId',0);
    }
  },
  //method
  hotCircleCilck: function (event) {
    var tapId = event.currentTarget.id;
    this.addHeaderUrl();
    wx.navigateTo({
      url: '/pages/marketing/yglDetail?id='+tapId+"&pageFlag=2"
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      showCircle: true
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    //暂停加载或数据已加载完了直接返回空
    if(this.data.listType==0){
      if (this.data.isloading || this.data.isLoadingEnd == 1) {
        console.log('end');
        return;
      }

      this.getList(parseInt(this.data.page) + 1, this.data.sort, 1);
    }else if(this.data.listType==2){
      if (this.data.isloading || this.data.isLoadingEndGl == 1) {
        console.log('end');
        return;
      }

      this.getListGl(parseInt(this.data.pageGl) + 1, this.data.sort, 1);
    }
  },

  //上拉获取数据
  getList(page, sort, pageAdd) {
    var that = this;
    this.setData({
      isloading: true
    });
    console.log('加载更多');
    wx.showLoading({
      title: '加载中'
    });

    wx.request({
      url: that.data.baseUrl + 'getForumListForWhere.php',
      method: 'POST',
      data: {
        'rid': that.data.id,
        'myOpenid': that.data.openid,
        'tableRow': 'openid',
        'openid': that.data.openid,
        'page': page,
        'sort': wx.getStorageSync('myQzSort')+1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (pageAdd == 1) {
            that.setData({
              page: parseInt(that.data.page) + 1
            });
          }
          that.setData({
            isLoadingEnd: res.data.isLoadingEnd,
            forumList: that.data.forumList.concat(res.data.forumList),
            isloading: false
          });
        } else {
          app.showTip(res.data.msg);
          that.setData({
            isloading: false,
            isLoadingEnd: 1
          });
        }
      },
      fail: function(res) {
        wx.hideLoading();
        that.setData({
          isloading: false,
          isLoadingEnd: 1
        })
      }
    });
  },


  //上拉获取数据--攻略
  getListGl(page, sort, pageAdd) {
    var that = this;
    this.setData({
      isloading: true
    });
    console.log('加载更多');
    wx.showLoading({
      title: '加载中'
    });

    wx.request({
      url: that.data.baseUrl + 'getForumListGlForWhere.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'page': page,
        'sort': wx.getStorageSync('myGlSort')+1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (pageAdd == 1) {
            that.setData({
              pageGl: parseInt(that.data.pageGl) + 1
            });
          }
          that.setData({
            isLoadingEndGl: res.data.isLoadingEnd,
            forumListGl: that.data.forumListGl.concat(res.data.forumList),
            isloading: false
          });
        } else {
          app.showTip(res.data.msg);
          that.setData({
            isloading: false,
            isLoadingEndGl: 1
          });
        }
      },
      fail: function(res) {
        wx.hideLoading();
        that.setData({
          isloading: false,
          isLoadingEndGl: 1
        })
      }
    });
  },

    //攻略点赞
    helpGl(e){
      var that = this;
    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addZanGl.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumListGl[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumListGl[' + index + '].is_zan']: "1",
              ['forumListGl[' + index + '].zan_number']: parseInt(that.data.forumListGl[index].zan_number) + 1
            })

          } else {
            that.setData({
              ['forumListGl[' + index + '].is_zan']: "0",
              ['forumListGl[' + index + '].zan_number']: parseInt(that.data.forumListGl[index].zan_number) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/square/index',
      imageUrl: that.data.shareImg,
      success: function(res) {

      },
      fail: function(res) {

      }
    }
  }
})